package com.tsvetanv.data.binding.validation;

import junit.framework.TestCase;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.ServletRequestDataBinder;

import com.tsvetanv.data.binding.model.validation.MutitypedCommandBean;

public class MultitypedCommandBeanValidationTest extends TestCase {

	private MutitypedCommandBean bean;
	private ServletRequestDataBinder binder;
	private MockHttpServletRequest request;

	@Override
	protected void setUp() throws Exception {
		bean = new MutitypedCommandBean();
		binder = new ServletRequestDataBinder(bean, "beanName");
		request = new MockHttpServletRequest();
	}

	public void testMultitypedCommandBeanValidation() {
		binder.setRequiredFields(new String[] { "intProperty",
				"integerProperty", "strings" });

		request.addParameter("intProperty", "123");
		// skip Integer property ==> we will get error
		request.addParameter("strings", new String[] { "Tsvetan", "Vasilev" });

		binder.bind(request);

		BindException errors = binder.getErrors();
		FieldError fieldError = errors.getFieldError("integerProperty");

		assertNotNull(fieldError);
		assertEquals("required", fieldError.getCode());

		assertEquals(new String[] { "Tsvetan", "Vasilev" }[0],
				bean.getStrings()[0]);
		assertEquals(new String[] { "Tsvetan", "Vasilev" }[1],
				bean.getStrings()[1]);

	}

	public void test2MultitypedCommandBeanValidation() {

		request.addParameter("charProperty", "Z");
		request.addParameter("intProperty", "NAN"); // NAN= Not_A_Number
		request.addParameter("classProperty", "java.lang.Object");

		binder.bind(request);

		BindException errors = binder.getErrors();
		FieldError intFieldError = errors.getFieldError("intProperty");
		assertNotNull(intFieldError);
		assertEquals("typeMismatch", intFieldError.getCode());
	}

}
